<template>
  <div class="purchase-order table-theme">
    <head-title title="订单--采购订单"></head-title>
    <el-card>
      <div class="order_list_head">
        <div class="type-view">
          <div
            class="client-item"
            v-for="(item, index) in classifyList"
            :key="item.index"
            @click="roleType(index)"
            :class="[type == index ? 'client-item-active' : '']"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <div class="data-filtering-view">
        <div class="data-filtering-left">
          <p>请选择</p>
          <div class="select-view">
            <el-date-picker
              @change="selectTime"
              v-model="time"
              type="daterange"
              align="right"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
        <div class="data-filtering-right">
          <el-button type="primary" style="margin-right: 15px;" @click="exportExcel">导出</el-button>
          <search-view
            :option="searchOption"
            @value="goSearch"
            @clear="refreshPage"
          ></search-view>
          <refresh-button @refresh="refreshPage"></refresh-button>
        </div>
      </div>
      <el-table :data="list" stripe style="margin-top: 20px">
        <el-table-column
          label="序号"
          align="center"
          prop="order_id"
          width="50"
        ></el-table-column>
        <el-table-column
          label="工厂ID"
          align="center"
          prop="factory_id"
          width="80"
        ></el-table-column>
        <el-table-column
          label="工厂名称"
          align="center"
          width="120"
          prop="factory_name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="订单号"
          align="center"
          prop="order_sn"
          width="130"
        ></el-table-column>
        <el-table-column
          label="商品名称"
          align="center"
          width="120"
          prop="goods_name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="商品编号"
          align="center"
          width="120"
          prop="goods_sn"
        ></el-table-column>
        <el-table-column
          label="SKU编号"
          align="center"
          prop="sku_sn"
          width="120"
        ></el-table-column>
        <el-table-column
          label="工厂货号"
          align="center"
          width="120"
          prop="lining_sn"
        ></el-table-column>
        <el-table-column label="商品图片" align="center" width="80">
          <template slot-scope="scope">
            <el-image :src="scope.row.img" style="width: 50px; height: 50px"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="库存"
          align="center"
          width="100"
          prop="stock"
        ></el-table-column>
        <el-table-column
          label="采购数量"
          align="center"
          width="100"
          prop="purchase_num"
        ></el-table-column>
        <el-table-column
          label="已入库数"
          align="center"
          width="100"
          prop="warehouse_num"
        ></el-table-column>
        <el-table-column label="工厂价" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.factory_price }}元
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.order_amount }}元
          </template>
        </el-table-column>
        <el-table-column label="规格" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.color }}、{{ scope.row.size }}、{{ scope.row.lining }}
          </template>
        </el-table-column>
        <el-table-column
          label="跟单员"
          align="center"
          width="100"
          prop="follow_user"
        ></el-table-column>
        <el-table-column
          label="时间"
          align="center"
          width="165"
          prop="add_time"
        ></el-table-column>
        <el-table-column
          label="状态"
          align="center"
          width="100"
          prop="status_name"
        ></el-table-column>
        <el-table-column
          label="采购备注"
          align="center"
          width="200"
          prop="follow_brief"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="下单员"
          align="center"
          width="100"
          prop="create_by"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="goDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="mini"  @click="exportExcelOrder(scope.row)">导出</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="factoryConfrim(scope.row)"
              v-if="scope.row.order_status == 1"
              >工厂确认</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="applyStorage(scope.row)"
              v-if="scope.row.order_status==2 || scope.row.order_status==3"
              >申请入库</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="init"
          :current-page.sync="page"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog :visible.sync="showDialog" title="申请入库" append-to-body :close-on-press-escape="false" width="680px">
      <div class="storage-info">
        <p><span>当前要申请入库的商品编号为：</span>{{ stockInfo.goods_sn }}</p>
        <p><span>sku编号为：</span>{{ stockInfo.sku_sn }}</p>
        <p><span>规格：</span>{{ stockInfo.color }}、{{ stockInfo.size }}、{{ stockInfo.lining }}</p>
        <p><span>可申请最大入库数：</span>{{ Number(stockInfo.purchase_num) - Number(stockInfo.warehouse_num) }}</p>
      </div>
      <el-form :model="storageForm" :rules="storageRules" ref="storageForm" label-width="85px">
        <el-form-item label="入库数量:" prop="num">
          <el-input placeholder="请输入申请入库说明" v-model="storageForm.num"></el-input>
        </el-form-item>
				<el-form-item label="入库说明:">
          <el-input type="textarea" :rows="6" placeholder="请输入申请入库说明" v-model="storageForm.brief"></el-input>
        </el-form-item>
        <el-form-item label="入库凭证:">
          <div class="upload-box" style="padding-left: 0;">
            <div class="goods-img-upload">
              <div class="goods-img-upload-btns">
                <el-upload ref="upload" action="fakeaction"
                  :show-file-list="false" :http-request="function (res) { return upload(res); }" multiple
                  accept="image/*"><el-button type="primary" size="small">上传图片</el-button>
                </el-upload>
              </div>
              <div class="goods-img-upload-imgs">
                <el-image v-if="!storageForm.voucher_img.length">
                  <div slot="error"></div>
                </el-image>
                <div v-for="(data, index) in storageForm.voucher_img" :key="index" class="vice_big_box" v-else>
                  <i class="el-icon-error" @click="delVoucher(index)"></i>
                  <el-image :preview-src-list="storageForm.voucher_img" :src="data" fit="contain"></el-image>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showDialog = false">取 消</el-button>
				<el-button type="primary" @click="submit('storageForm')">确 定</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      type: 0,
      classifyList: [
        {
          label: "全部",
          value: "",
        },
        {
          label: "待工厂确认",
          value: 1,
        },
        {
          label: "待入库",
          value: 2,
        },
        {
          label: "部分入库",
          value: 3,
        },
        {
          label: "已完成",
          value: 4,
        },
      ],
      searchOption: [
        {
          value: 0,
          label: "采购订单编号",
          key: 'order_sn',
        },
        {
          value: 1,
          label: "商品编号",
          key: 'goods_sn',
        },
        {
          value: 2,
          label: "工厂编号",
          key: 'factory_sn',
        },
        {
          value: 3,
          label: "工厂名称",
          key: 'factory_name',
        },
        {
          value: 4,
          label: "下单员",
          key: 'create_by',
        },
        {
          value: 5,
          label: "SKU编号",
          key: 'sku_sn',
        },
        {
          value: 6,
          label: "工厂货号",
          key: 'goods_sn',
        },
      ],
      searchType: "",
      searchContent: "",
      time: [],
      page: 1,
      total: 0,
      list: [],
      showDialog: false,
      storageForm: {
        order_id: '',
        num: '',
        brief: '',
        voucher_img: [],
      },
      storageRules: {
        num: [{ required: true,message: '请输入入库数量',trigger: 'blur' }]
      },
      stockInfo: ''
    };
  },
  watch: {
    showDialog(n,o){
      if(!n){
        this.storageForm = this.$options.data().storageForm
      }
    }
  },
  mounted(){
    this.init()
  },
  methods: {
    init() {
      let data = {
        page: this.page - 1,
        status: this.classifyList[this.type].value,
        start_time: this.time && this.time.length?this.time[0]:'',
        end_time: this.time && this.time.length?this.time[1]:'',
      }
      if(this.searchType!==''){
        data[this.searchOption[this.searchType].key] = this.searchContent
      }
      this.$http(this.$ApiList.PurchaseOrderList,data).then(res => {
        if(res.code==200){
          this.list = res.datas.list
          this.total = res.datas.count
          console.log(this.total)
        }
      })
    },
    goSearch(searchType, searchContent) {
      this.searchType = searchType;
      this.searchContent = searchContent;
      this.page = 1;
      this.init();
    },
    // 刷新
    refreshPage() {
      this.searchType = 0;
      this.searchContent = "";
      this.page = 1;
      this.init();
    },
    selectTime() {
      this.page = 1;
      this.init();
    },
    roleType(index) {
      this.type = index;
      this.page = 1;
      this.init()
    },
    factoryConfrim(row) {
      let content = `<p>商品编号：${row.goods_sn}</p><p>工厂货号：${row.lining_sn}</p><p>商品出厂价：${row.factory_sn}</p><p>订单总额：${row.order_amount}</p><p>商品规格：${row.color}、${row.size}、${row.lining}</p><p>商品数：${row.purchase_num}</p>`
      this.$confirm(content, "温馨提示：请确认商品信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true,
      })
        .then(() => {
          this.$http(this.$ApiList.PurchaseOrderFactoryConfirm,{order_id: row.order_id,factory_sn: row.factory_sn}).then(res => {
            this.$layer.msg('确认成功')
            this.init()
          })
        })
        .catch(() => {
          // 取消
        });
    },
    applyStorage(row){
      this.stockInfo = row
      this.storageForm.order_id = row.order_id
      this.showDialog = true
    },
    upload(params) {
      if (this.storageForm.voucher_img.length >= 5) {
        return this.$layer.msg(`最多上传5张`);
      }
      const file = params.file,
        isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png',
        isLt3MB = file.size / 1024 <= 3024;
      if (!isJPGPNG) {
        this.$layer.msg('只能上传图片格式png、jpg!');
        return;
      }
      if (!isLt3MB) {
        this.$layer.msg('图片不能大于3M');
        return;
      }
      let img = new FormData();
      img.append('file[]', file);
      this.$http(this.$ApiList.publicUpload, img).then(res => {
        if (this.storageForm.voucher_img.length >= 5) return
        this.storageForm.voucher_img.push(res.datas[0])
      });
    },
    delVoucher(index){
      this.storageForm.voucher_img.splice(index,1)
    },
    goDetail(row){
      this.$router.push(`/purchase_order_detail?order_id=${row.order_id}`)
    },
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {}
          for(let i in this.storageForm){
            if(i!=='voucher_img'){
              data[i] = this.storageForm[i]
            }else{
              data[i] = this.storageForm[i].join(',')
            }
          }
          this.$http(this.$ApiList.PurchaseOrderWarehousing,data).then(res => {
            this.$layer.msg('申请入库成功');
            this.showDialog = false
            this.init()
          })
        } else {
          this.$layer.msg('请填写完整信息后提交');
        }
      });
    },
    exportExcel(){
      let param = {
        status: this.classifyList[this.type].value,
        start_time: this.time && this.time.length?this.time[0]:'',
        end_time: this.time && this.time.length?this.time[1]:'',
      }
      if(this.searchType!==''){
        param[this.searchOption[this.searchType].key] = this.searchContent
      }
      let paramString = Object.keys(param).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(param[key])}`).join('&')
      window.location.href = `${this.$domain}furniture/Adminexcel/GetPurchaseOrderExcel?${paramString}`
    },
    exportExcelOrder(row){
      window.location.href = `${this.$domain}furniture/Adminexcel/GetPurchaseOrderExcel?order_sn=${row.order_sn}`
    }
  },
};
</script>

<style lang="scss">
.vl-notify{
	z-index: 10000;
}
</style>
<style lang="scss" scoped>
.order_list_head {
  display: flex;
}
.type-view {
  display: flex;
  flex: 1;
  min-width: 0;
}
.type-view .client-item {
  margin-right: 40px;
  line-height: 40px;
  color: rgba(153, 153, 153, 1);
  cursor: pointer;
}
.client-item-active {
  color: #333333 !important;
  border-bottom: 4px solid #34a1e0;
}
.data-filtering-view {
  margin-top: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .data-filtering-left {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
    .select-view {
      margin-left: 10px;
    }
  }
  .data-filtering-right {
    display: flex;
    align-items: center;
  }
}
.storage-info{
  line-height: 30px;
  margin-bottom: 15px;
  font-size: 12px;
  p{
    color: #333;
    font-weight: bold;
    span{
      font-weight: normal;
      color: #888;
    }
  }
}
.upload-box {
	// padding-left: 40px;

	.goods-img-upload {
		display: flex;

		.goods-img-upload-imgs {
			flex: 1;
			align-items: flex-start;

			.el-image {
				width: 140px;
				height: 140px;
				border: solid 1px #e5e5e5;
				margin-left: 25px;
				vertical-align: top;
			}
		}

		.goods-img-upload-imgs-info {
			width: 100%;
			max-width: 660px;
			border: solid 1px #e5e5e5;
			margin-left: 25px;
			min-height: 390px;

			.goods-img-upload-imgs-info-box {
				position: relative;

				.el-icon-error {
					position: absolute;
					font-size: 20px;
					color: #ef3030;
					right: 5px;
					top: 5px;
					z-index: 1;
					background-color: #fff;
					border-radius: 50%;
					cursor: pointer;
				}
			}

			.el-image {
				width: 100%;
				vertical-align: top;
			}
		}

		.vice_big_box {
			position: relative;
			display: inline-block;
			vertical-align: top;
			margin-bottom: 20px;

			.el-icon-error {
				position: absolute;
				font-size: 20px;
				color: #ef3030;
				right: 5px;
				top: 5px;
				z-index: 1;
				background-color: #fff;
				border-radius: 50%;
				cursor: pointer;
			}
		}
	}
}
</style>